package com.wh.controller;

import com.wh.bean.UserInfo;
import com.wh.service.IUserInfoService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
public class UserInfoController {
	
	private static Logger LOGGER = LoggerFactory.getLogger(UserInfoController.class);
	
	@Resource
	private IUserInfoService service;
	
	@RequestMapping(value = "/")
	public ModelAndView login(ModelAndView mv){
		mv.setViewName("/index");
		return mv;
	}
	
	
	
	@RequestMapping(value = "/home")
	public ModelAndView home(ModelAndView mv){
		mv.setViewName("/home");
		return mv;
	}

	
	@RequestMapping(value="/login", method = RequestMethod.POST)
	public ModelAndView testUserInfo(HttpServletRequest request, ModelAndView mv, UserInfo info){
		HttpSession session = request.getSession();
		try {
			List<UserInfo> list = service.selectUserInfo(info.getUserPassword());
			if (list != null && list.size() > 0) {
				session.setAttribute("userInfo", list.get(0));
				//mv.addObject("userName", list.get(0).getName());
				mv.setViewName("redirect:/home");
//				mv.setViewName("/index/home");
			}
		} catch (Exception e) {
			LOGGER.error("testUserInfo error:" + e);
		}
		return mv;
	}
	
	@RequestMapping(value="findUserInfoList")
	@ResponseBody
	public Object findUserInfoList(UserInfo userInfo){
		List<UserInfo> list = new ArrayList<UserInfo>();
		try {
			list = service.findUserInfoList(userInfo);
			LOGGER.info("排序前：" + list.toString());
			Collections.sort(list, new Comparator<UserInfo>() {
				@Override
				public int compare(UserInfo o1, UserInfo o2) {
					return o1.getUserCode().compareTo(o2.getUserCode());
				}
			});
			LOGGER.info("排序后：" + list.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@RequestMapping("/addName")
	public void addName(HttpServletResponse response) throws IOException {
		//设置响应字符编码
		response.setCharacterEncoding("UTF-8");
		//获取本地文件
		String filePath = "G:\\HBuilder\\bqjrlogin\\score.html";
		File file = new File(filePath);
		Document doc = Jsoup.parse(file, "UTF-8");
		//获取td标签集合
		Elements tds = doc.getElementsByTag("td");
		//在td集合标签中，在第九个添加text
		tds.get(9).appendText("张大胖");
		response.getWriter().write(doc.toString());
		response.getWriter().flush();
		response.getWriter().close();
	}

}
